package com.atguigu.sparsearray;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 二维数组转稀疏数组并保存到本地的实现(模拟下五子棋)
 * @author WangJX
 * @version 1.0
 * @date 2019/9/15 23:44
 */
public class SparseArray {
    public static void main(String[] args) throws IOException {
        //定义一个11x11的棋盘
        int chessArr[][] = new int[11][11];
        chessArr[1][2] = 1;
        chessArr[2][3] = 2;


        //打印数组
        for (int[] ints : chessArr) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }

        //得到有用数据的个数
        int sum = 0;
        for (int[] ints : chessArr) {
            for (int anInt : ints) {
                if (anInt != 0){
                    sum++;
                }
            }
        }
        System.out.printf("\n有用数据的个数为：%d\n", sum);

        //把数组变成稀疏数组
        int sparseArr[][] = new int[sum + 1][3];
        //获得二维数组每一行的个数
        sparseArr[0][0] = chessArr.length;
        //获得二维数组每一列的个数
        sparseArr[0][1] = chessArr[0].length;
        //获得二维数组中有效数的个数
        sparseArr[0][2] = sum;
        //遍历循环二维数组，并转化为稀疏数组
        int count = 0;
        for (int i = 0; i < chessArr.length; i++) {
            for (int j = 0; j < chessArr[0].length; j++) {
                if (chessArr[i][j] != 0){
                    sparseArr[count + 1][0] = i;
                    sparseArr[count + 1][1] = j;
                    sparseArr[count + 1][2] = chessArr[i][j];
                    count++;
                }
            }
        }

        //打印稀疏数组
        System.out.println("转化为的稀疏数组为:");
        for (int[] ints : sparseArr) {
            for (int anInt : ints) {
                System.out.printf("%d\t", anInt);
            }
            System.out.println();
        }

        //输出保存
        FileOutputStream outputStream = new FileOutputStream("E:\\new\\sparseArr.txt");

        for (int[] ints : sparseArr) {
            for (int anInt : ints) {
                outputStream.write(anInt);
            }
        }

        outputStream.close();
    }
}
